package com.ibeeking.found.msg.rest.service.impl;

import com.ibeeking.found.common.utils.BlobUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IEmailTemplateService;
import com.ibeeking.found.msg.service.common.dos.EmailTemplateDO;
import com.ibeeking.found.msg.service.common.dos.EmailTemplateParamDO;
import com.ibeeking.found.msg.service.common.param.EmailTemplateParam;
import com.ibeeking.found.msg.service.common.query.EmailTemplateQuery;
import com.ibeeking.found.msg.service.common.vo.EmailTemplateParamVO;
import com.ibeeking.found.msg.service.common.vo.EmailTemplateVO;
import com.ibeeking.found.msg.service.mapper.EmailTemplateMapper;
import com.ibeeking.found.msg.service.mapper.EmailTemplateParamMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IEmailConfigService
 * description 邮件模板配置服务
 *
 * @Author ibeeking
 * @Date 2020-12-09 10:54
 */
@Service
public class EmailTemplateServiceImpl extends ServiceImpl<EmailTemplateMapper, EmailTemplateDO> implements IEmailTemplateService {


    @Resource
    private EmailTemplateMapper emailTemplateMapper;

    @Resource
    private EmailTemplateParamMapper emailTemplateParamMapper;
    /**
     * 邮件服务器列表
     *
     * @param
     * @return
     */
    @Override
    public List<EmailTemplateVO> list(EmailTemplateQuery query) {
        List<EmailTemplateDO> emailTemplateDOS = emailTemplateMapper.selectList(new LambdaQueryWrapper<EmailTemplateDO>()
                .eq(query.getId() != null , EmailTemplateDO::getId, query.getId())
                .eq(StringUtils.isNotEmpty(query.getTemplateCode()), EmailTemplateDO::getTemplateCode, query.getTemplateCode())
                .eq(StringUtils.isNotEmpty(query.getTemplateName()), EmailTemplateDO::getTemplateName, query.getTemplateName())
                .eq(query.getPublishStatus() != null, EmailTemplateDO::getPublishStatus, query.getPublishStatus())
        );
        List<EmailTemplateVO> emailTemplateVOS = new ArrayList<>();
        if(Collections3.isNotEmpty(emailTemplateDOS)){
            emailTemplateVOS = emailTemplateDOS.stream().map(d->{
                EmailTemplateVO emailTemplateVO = BeanUtil.convertBean(d, EmailTemplateVO.class);
                Object obj = d.getTemplateContent();
                if(obj != null){
                    emailTemplateVO.setTemplateContent(new String((byte[]) obj, StandardCharsets.UTF_8));
                }
                return emailTemplateVO;
            }).collect(Collectors.toList());
        }
        return emailTemplateVOS;
    }
    /**
     * 邮件服务器列表
     *
     * @param
     * @return
     */
    @Override
    public List<EmailTemplateVO> listEmailTemplate() {
        List<EmailTemplateDO> emailTemplateDOS = emailTemplateMapper.selectList(new LambdaQueryWrapper<EmailTemplateDO>());
        List<EmailTemplateVO> emailTemplateVOS = new ArrayList<>();
        if(Collections3.isNotEmpty(emailTemplateDOS)){
            emailTemplateVOS = emailTemplateDOS.stream().map(d->{
                EmailTemplateVO emailTemplateVO = BeanUtil.convertBean(d, EmailTemplateVO.class);
                Object obj = d.getTemplateContent();
                if(obj != null){
                    emailTemplateVO.setTemplateContent(new String((byte[]) obj, StandardCharsets.UTF_8));
                }
                return emailTemplateVO;
            }).collect(Collectors.toList());
        }
        return emailTemplateVOS;
    }
    /**
     * 邮件参数列表
     *
     * @param
     * @return
     */
    @Override
    public List<EmailTemplateParamVO> listEmailTemplateParam(Long templateId) {
        List<EmailTemplateParamDO> emailTemplateParamDOS = emailTemplateParamMapper.selectList(new LambdaQueryWrapper<EmailTemplateParamDO>()
                .eq(EmailTemplateParamDO::getTemplateId, templateId)
        );
        List<EmailTemplateParamVO> emailTemplateParamVOS = JsonUtils.jsonToList(emailTemplateParamDOS, EmailTemplateParamVO.class);
        return emailTemplateParamVOS;
    }
    /***
     * 修改模板
     */
    @Override
    public Boolean modifyEmailTemplate(EmailTemplateParam emailTemplateParam) {
        Long userId = UserUtils.getUserId();

        String templateContent = emailTemplateParam.getTemplateContent();
        Blob blobTemplateContent = BlobUtils.string2blob(templateContent);
        EmailTemplateDO emailTemplateDO = BeanUtil.convertBean(emailTemplateParam, EmailTemplateDO.class);
        emailTemplateDO.setModifyBy(userId);
        emailTemplateDO.setModifyTime(LocalDateTime.now());
        emailTemplateDO.setTemplateContent(blobTemplateContent);

        return emailTemplateMapper.updateById(emailTemplateDO) > 0;
    }

    @Override
    public Boolean changePublishStatus(Long id, Integer status) {
        Long userId = UserUtils.getUserId();
        EmailTemplateDO emailTemplateDO =  emailTemplateMapper.selectById(id);
        if(emailTemplateDO == null){
            throw new BusinessException("记录不存在");
        }
        emailTemplateDO.setPublishStatus(status);
        emailTemplateDO.setModifyBy(userId);
        emailTemplateDO.setModifyTime(LocalDateTime.now());
        return emailTemplateMapper.updateById(emailTemplateDO) > 0;
    }

    /***
     * 通过id查询模板
     */
    @Override
    public EmailTemplateVO viewEmailTemplate(Long id) {
        EmailTemplateDO emailTemplateDO = emailTemplateMapper.selectById(id);
        if(emailTemplateDO == null){
            throw new BusinessException("查询数据不存在");
        }
        EmailTemplateVO emailTemplateVO = BeanUtil.convertBean(emailTemplateDO, EmailTemplateVO.class);
        Object obj = emailTemplateDO.getTemplateContent();
        if(obj != null) {
            emailTemplateVO.setTemplateContent(new String((byte[])obj, StandardCharsets.UTF_8));
        }
        return emailTemplateVO;
    }
    /***
     * 通过id查询模板
     */
    @Override
    public EmailTemplateVO queryTemplateByCode(String code) {
        EmailTemplateDO emailTemplateDO = emailTemplateMapper.selectOne(new LambdaQueryWrapper<EmailTemplateDO>()
                .eq(EmailTemplateDO::getTemplateCode, code));
        if(emailTemplateDO == null){
            throw new BusinessException("查询数据不存在");
        }
        EmailTemplateVO emailTemplateVO = BeanUtil.convertBean(emailTemplateDO, EmailTemplateVO.class);
        Object obj = emailTemplateDO.getTemplateContent();
        if(obj != null) {
            emailTemplateVO.setTemplateContent(new String((byte[])obj, StandardCharsets.UTF_8));
        }
        return emailTemplateVO;
    }
}
